import { _decorator, Component, Button, Label, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GUIButton')
export class GUIButton extends Component {
    @property(Button)
    button: Button | null = null;

    @property(Label)
    label: Label | null = null;

    @property(Node)
    disableNode: Node = null!;

    private _clickFn: ((param: string) => void) | null = null;
    private labelName: string = '';

    onLoad() {
        if (this.button) {
            this.button.node.on(
                Button.EventType.CLICK,
                this._onClick,
                this,
            );
        }
    }

    onDestroy() {
        if (this.button) {
            this.button.node.off(
                Button.EventType.CLICK,
                this._onClick,
                this,
            );
        }
    }

    private _onClick() {
        if (!this.enabled) {
            return;
        }
        if (this._clickFn) {
            this._clickFn(this.labelName);
        }
    }

    /**
     * 初始化按钮组件
     * @param name 按钮名称（用于 label 和点击回调参数）
     * @param clickFn 点击事件回调
     */
    public init(name: string, clickFn: (param: string) => void) {
        this.labelName = name;
        this._clickFn = clickFn;

        if (this.label) {
            this.label.string = name;
        }
    }

    protected onEnable(): void {
        this.disableNode.active = false;
    }

    protected onDisable(): void {
        this.disableNode.active = true;
    }
    
}
